#coding=utf-8

import json

from tornado.gen    import coroutine, Return
from tornado.log    import access_log as logger

from core.scanner   import ControllerManager
from core.ViewMaker import JsonView
from core.error     import UserError
from utils.jwter    import JwtGenerator

from pojo.json.JsonMsg import MsgMaker

from services.organ import api
from .tools import name_pwd_validator


'''
reigster controller
'''

@ControllerManager.register(r'/api/auth/register', ('post'))
@coroutine
def org_register(req):
    try:
        req_body = json.loads(req.get_body())

        login_name = req_body['username']
        password = req_body['password']

        # validate login_name and password
        name_pwd_validator(login_name, password)

        ret, msg = api.org_register(login_name, password)

        if not ret:
            raise UserError(msg)

    except UserError as e:
        #error catch
        logger.error('%s:%s' % (e.__class__.__name__, e.message))
        raise Return(JsonView(MsgMaker.badMsg(msg = e.message)))
        # 返回错误信息
    raise Return(JsonView(MsgMaker.goodMsg()))
    # 返回

'''
login controller
'''

@ControllerManager.register(r'/api/auth/login', ('post'))
@coroutine
def org_login(request):
    try:

        req_body = json.loads(request.get_body())

        login_name = req_body['login_name']
        password = req_body['password']

        # validate login_name and password
        name_pwd_validator(login_name, password)

        ret, msg = api.get_org_by_name_pwd(login_name, password)

        if not ret:
            raise UserError(msg)
        else:
            user_id = ret['user_id']
            user_name = ret['login_name']
            jwt = JwtGenerator(user_id, 24 * 3600 * 15)


    except UserError as e:
        # do someting
        logger.error('%s:%s' % (e.__class__.__name__, e.message))
        raise Return(JsonView(MsgMaker.badMsg(e.message)))  # 返回错误信息

    raise Return(JsonView(MsgMaker.goodMsg(data = {
        'access_token': jwt.get(),
        'user_id': user_id,
        'user_name': user_name
    })))  # 返回

